<?php
// +----------------------------------------------------------------------
// | likeadmin快速开发前后端分离管理后台（PHP版）
// +----------------------------------------------------------------------
// | 欢迎阅读学习系统程序代码，建议反馈是我们前进的动力
// | 开源版本可自由商用，可去除界面版权logo
// | gitee下载：https://gitee.com/likeshop_gitee/likeadmin
// | github下载：https://github.com/likeshop-github/likeadmin
// | 访问官网：https://www.likeadmin.cn
// | likeadmin团队 版权所有 拥有最终解释权
// +----------------------------------------------------------------------
// | author: likeadminTeam
// +----------------------------------------------------------------------

namespace app\adminapi\logic\recharge_template;


use app\common\model\promotion\PromotionLink;
use app\common\model\recharge_template\RechargeTemplate;
use app\common\logic\BaseLogic;
use app\common\model\recharge_template\RechargeTemplateDetail;
use think\facade\Db;


/**
 * RechargeTemplate逻辑
 * Class RechargeTemplateLogic
 * @package app\adminapi\logic
 */
class RechargeTemplateLogic extends BaseLogic
{


    /**
     * @notes 添加
     * @param array $params
     * @return bool
     * @author likeadmin
     * @date 2024/01/13 14:45
     */
    public static function add(array $params, array $details,$admin_id=0): bool
    {
        Db::startTrans();
        try {
            $result = RechargeTemplate::create([
                'name' => $params['name'],
                'app_id' => $params['app_id'],
                'admin_id' => $admin_id,
            ]);
            foreach ($details as $k=>$v){
                $data = [];
                $data['recharge_template_id'] = $result->id;
                $data['type'] = $v['type'];
                $data['is_first'] = $v['is_first'];
                $data['money'] = $v['money'];
                $data['original_money'] = $v['original_money'];
                $data['tag_name'] = $v['tag_name']??null;
                $data['sort'] = $v['sort']??0;
                if ($data['type']==1){
                    $data['k_coin'] = $v['k_coin'];
                    $data['z_coin'] = $v['z_coin'];
                }
                RechargeTemplateDetail::create($data);
            }
            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            self::setError($e->getMessage());
            return false;
        }
    }


    /**
     * @notes 编辑
     * @param array $params
     * @return bool
     * @author likeadmin
     * @date 2024/01/13 14:45
     */
    public static function edit(array $params, array $details): bool
    {
        Db::startTrans();
        try {
            $datas = [];
            if(isset($params['name'])&&!empty($params['name'])){
                $datas['name'] = $params['name'];
            }
            RechargeTemplate::where('id', $params['id'])->update($datas);
            RechargeTemplateDetail::where('recharge_template_id', $params['id'])->delete();
            foreach ($details as $k=>$v){
                $data = [];
                $data['recharge_template_id'] = $params['id'];
                $data['type'] = $v['type'];
                $data['is_first'] = $v['is_first'];
                $data['money'] = $v['money'];
                $data['original_money'] = $v['original_money'];
                $data['tag_name'] = $v['tag_name']??null;
                $data['sort'] = $v['sort']??0;
                if ($data['type']==1){
                    $data['k_coin'] = $v['k_coin'];
                    $data['z_coin'] = $v['z_coin'];
                }
                RechargeTemplateDetail::create($data);
            }
            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            self::setError($e->getMessage());
            return false;
        }
    }

    /**
     * @notes 复制
     * @param array $params
     * @return bool
     * @author likeadmin
     * @date 2024/01/13 14:45
     */
    public static function copy(array $params): bool
    {
        Db::startTrans();
        try {
            $rechargeTemplate = RechargeTemplate::where('id',$params['id'])->findOrEmpty();
            $rechargeTemplateDetailsList = RechargeTemplateDetail::where('recharge_template_id',$rechargeTemplate['id'])->column('type,money,original_money,k_coin,z_coin,tag_name,sort,is_first');
            $result = RechargeTemplate::create([
                'name' => $rechargeTemplate['name'],
                'app_id' => $rechargeTemplate['app_id'],
                'admin_id' => $params['admin_id'],
            ]);
            foreach ($rechargeTemplateDetailsList as $k=>$v){
                $data = [];
                $data['recharge_template_id'] = $result->id;
                $data['type'] = $v['type'];
                $data['is_first'] = $v['is_first'];
                $data['money'] = $v['money'];
                $data['original_money'] = $v['original_money'];
                $data['tag_name'] = $v['tag_name']??null;
                $data['sort'] = $v['sort']??0;
                $data['k_coin'] = $v['k_coin'];
                $data['z_coin'] = $v['z_coin'];
                RechargeTemplateDetail::create($data);
            }
            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            self::setError($e->getMessage());
            return false;
        }
    }


    /**
     * @notes 删除
     * @param array $params
     * @return bool
     * @author likeadmin
     * @date 2024/01/13 14:45
     */
    public static function delete(array $params): bool
    {

        Db::startTrans();
        try {
            $promotionLink = PromotionLink::where('recharge_template_id',$params['id'])->findOrEmpty();
            if (!$promotionLink->isEmpty()){
                self::setError('模板已被推广链绑定，无法删除');
                return false;
            }
            RechargeTemplate::destroy($params['id']);
            RechargeTemplateDetail::where('recharge_template_id',$params['id'])->delete();
            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            self::setError($e->getMessage());
            return false;
        }
    }


    /**
     * @notes 获取详情
     * @param $params
     * @return array
     * @author likeadmin
     * @date 2024/01/13 14:45
     */
    public static function detail($params): array
    {
        $details = RechargeTemplate::field('id,name')->findOrEmpty($params['id'])->toArray();
        if (!empty($details)){
            $details['first_details'] = RechargeTemplateDetail::where('recharge_template_id',$params['id'])->where('is_first',1)->field('id,recharge_template_id,type,money,original_money,k_coin,z_coin,tag_name,sort,is_first')->order('sort asc')->select();
            $details['second_details'] = RechargeTemplateDetail::where('recharge_template_id',$params['id'])->where('is_first',2)->field('id,recharge_template_id,type,money,original_money,k_coin,z_coin,tag_name,sort,is_first')->order('sort asc')->select();
        }
        return $details;
    }

    /**
     * @notes  更改状态
     * @param array $params
     * @return bool
     * @author heshihu
     * @date 2022/2/21 18:04
     */
    public static function updateStatus(array $params)
    {
        RechargeTemplate::update([
            'id' => $params['id'],
            'status' => $params['status']
        ]);
        return true;
    }

    /*
 * 生成推广链接时使用
 * */
    public static function getAll($admin_id,$app_id): array
    {
        return RechargeTemplate::where('status',1)->where('app_id',$app_id)->where('admin_id',$admin_id)->field('id,name')->order('id asc')->select()->toArray();
    }
}